package com.example.restaurant.netty;


import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;
import com.example.restaurant.entity.Chat;
import com.example.restaurant.service.ChatService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.Charset;
import java.sql.Time;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@Configuration
@ChannelHandler.Sharable
public class CoordinationSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public Map<String, Channel> cmap = new HashMap<>();

    @Autowired
    private ChatService chatService;
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        System.out.println("与客户端建立连接，通道开启！");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与客户端断开连接，通道关闭！");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {

//        if (msg instanceof FullHttpRequest) {
//            FullHttpRequest req = (FullHttpRequest) msg;
//            String queryString = req.uri().split("\\?")[1];
//            QueryStringDecoder queryStringDecoder = new QueryStringDecoder(queryString, Charset.forName("UTF-8"));
//            String userid = queryStringDecoder.parameters().get("user").get(0);
//            System.out.println(userid);
//            // TODO: handle w and t parameters
//        } else {
//            super.channelRead(ctx, msg);
//        }
        if (msg instanceof FullHttpRequest) {
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        } else {
            String data1 = "";
            ByteBuf byteBuf = msg.content();

            if (byteBuf.hasArray()) {
                // 如果字节缓冲区有直接支持的字节数组，则可以使用该数组来提取数据
                byte[] dataBytes = byteBuf.array();
                int offset = byteBuf.arrayOffset() + byteBuf.readerIndex();
                int length = byteBuf.readableBytes();

                // 使用 dataBytes 数组来操作数据
                String data = new String(dataBytes, offset, length);
                System.out.println("Extracted data: " + data);
                data1 = data;
            } else {
                // 如果字节缓冲区没有直接支持的字节数组，则需要使用其他方法来提取数据
                byte[] dataBytes = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(byteBuf.readerIndex(), dataBytes);

                // 使用 dataBytes 数组来操作数据
                String data = new String(dataBytes);
                System.out.println("Extracted data: " + data);  //{"type":"SEND_HEART_TEST_REQUEST","body":{"message":"心跳检测"}}
                data1 = data;
            }

            JSONObject jsonObject = JSON.parseObject(data1);

            // 提取 type 字段的值
            String type = jsonObject.getString("type");

            // 提取 body 字段的值
            JSONObject bodyObject = jsonObject.getJSONObject("body");
            String message = bodyObject.getString("message");


            // 判断消息类型
            if (type.equals("SEND_HEART_TEST_REQUEST")) {
                // 处理心跳消息
//                System.out.println("接收到心跳消息: " + message);


                // 构建心跳回应消息
                JSONObject responseJson = new JSONObject();
                responseJson.put("type", "HEARTBEAT_SUCCESS");
                responseJson.put("message", "心跳成功");
                String responseMessage = responseJson.toJSONString();

                // 创建 TextWebSocketFrame 对象
                TextWebSocketFrame responseFrame = new TextWebSocketFrame(responseMessage);

                // 发送心跳回应消息给客户端
                ctx.writeAndFlush(responseFrame);

            }else if (type.equals("user")){
                send(bodyObject);
                String responseData = "{\"success\": true}";

                // 创建 FullHttpResponse 对象
                FullHttpResponse response = new DefaultFullHttpResponse(
                        HttpVersion.HTTP_1_1,
                        HttpResponseStatus.OK,
                        ByteBufUtil.writeUtf8(ctx.alloc(), responseData)
                );

                // 设置响应头信息
                response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json");
                response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());

                // 发送响应数据给客户端
                ctx.writeAndFlush(response);
            }
        }
//        System.out.println(String.format("收到客户端%s的数据：%s", ctx.channel().id(), msg.text()));
//        channelGroup.writeAndFlush(new TextWebSocketFrame("aaabbb"));
    }

//        //接收的消息
//        Map map = JSON.parseObject(msg.text(), Map.class);
//        String type = map.get("type").toString();
//        switch (type){
//            case "1":   // 登录
//                websocketLogin(map,ctx);
//                break;
//            case "2": // 发送对话消息
//                send(map);
//                break;
//            case "3":   // 请求进行视频通话
//                call(map);
//                break;
//            case "4":   // 对方回应通话
//                response(map);
//                break;
//            case "5":   //传递请求off
//                askoff(map);
//                break;
//            case "6":   //获取off
//                getoff(map);
//                break;
//            case "7":
//                answer(map);
//                break;
//            case "8":
//                candidate(map);
//                break;
//        }
//        System.out.println(String.format("收到客户端%s的数据：%s", ctx.channel().id(), msg.text()));
//        channelGroup.writeAndFlush(new TextWebSocketFrame("aaabbb"));

//    @Override
//    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        Object msg1 = msg;
//        System.out.println(msg);
//        String uri = ((FullHttpRequest) msg).uri();
//        System.out.println("uri: " + uri);
//        //输出带参数的uri , 然后截取出来需要的参数
//        if (null != uri && uri.contains("/websocket") && uri.contains("?")) {
//            String[] uriArray = uri.split("\\?");
//            if (null != uriArray && uriArray.length > 1) {
//                String[] paramsArray = uriArray[1].split("=");
//                if (null != paramsArray && paramsArray.length > 1) {
//                    // 参数获取
//                    String param= paramsArray[1];
//                    System.out.println(param);
////                    TextWebSocketFrame imsg = (TextWebSocketFrame) msg1;
////                    channelRead0(ctx, imsg);
//                }
//                System.out.println("握手成功");
//            }
//        }

//        System.out.println(msg);
//        ByteBuf byteBuf = msg.content();
//
//        if (byteBuf.hasArray()) {
//            // 如果字节缓冲区有直接支持的字节数组，则可以使用该数组来提取数据
//            byte[] dataBytes = byteBuf.array();
//            int offset = byteBuf.arrayOffset() + byteBuf.readerIndex();
//            int length = byteBuf.readableBytes();
//
//            // 使用 dataBytes 数组来操作数据
//            String data = new String(dataBytes, offset, length);
//            System.out.println("Extracted data: " + data);
//        } else {
//            // 如果字节缓冲区没有直接支持的字节数组，则需要使用其他方法来提取数据
//            byte[] dataBytes = new byte[byteBuf.readableBytes()];
//            byteBuf.getBytes(byteBuf.readerIndex(), dataBytes);
//
//            // 使用 dataBytes 数组来操作数据
//            String data = new String(dataBytes);
//            System.out.println("Extracted data: " + data);
//        }

//        //接收的消息
//        Map map = JSON.parseObject(msg.text(), Map.class);
//        String type = map.get("type").toString();
//        switch (type){
//            case "1":   // 登录
//                websocketLogin(map,ctx);
//                break;
//            case "2": // 发送对话消息
//                send(map);
//                break;
//            case "3":   // 请求进行视频通话
//                call(map);
//                break;
//            case "4":   // 对方回应通话
//                response(map);
//                break;
//            case "5":   //传递请求off
//                askoff(map);
//                break;
//            case "6":   //获取off
//                getoff(map);
//                break;
//            case "7":
//                answer(map);
//                break;
//            case "8":
//                candidate(map);
//                break;
//        }
//        System.out.println(String.format("收到客户端%s的数据：%s", ctx.channel().id(), msg.text()));
//        channelGroup.writeAndFlush(new TextWebSocketFrame("aaabbb"));
//    }



    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
        // 解析请求数据
        String requestData = req.content().toString(CharsetUtil.UTF_8);
        System.out.println("Received data from client during handshake: " + requestData);

        // 在这里处理接收到的数据
        // 解析 JSON 数据，提取相关字段
        JSONObject jsonObject = JSON.parseObject(requestData);
        String user = jsonObject.getString("user");
        System.out.println(user);
    }

//"body":{"type":"text","userid":"1","username":"用户1","userImg":"/image////","toUser":"2","message":{"text":"11111"},"createTime":1703130925468}}
    private void send(JSONObject body) {

        String sendid = body.getString("userid");
        String toUserid = body.getString("toUser");
        Integer createTime = body.getInteger("createTime");

        //格式化时间
        Instant instant = Instant.ofEpochMilli(createTime);
        LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        System.out.println(dateTime);
        JSONObject message = body.getJSONObject("message");
        String text = message.getString("text");
        Chat chat = new Chat();
        chat.setSendid(sendid);
        chat.setReceiverid(toUserid);
        chat.setMessage(text);
        LocalDateTime currentDateTime = LocalDateTime.now(); // 获取当前时间
        Timestamp timestamp = Timestamp.valueOf(currentDateTime);
        chat.setSendtime(timestamp);
        chat.setIs_read(1);

        try {
            chatService.save(chat);
            // 构建心跳回应消息
            JSONObject responseJson = new JSONObject();
//        responseJson.put("type", "HEARTBEAT_SUCCESS");
            responseJson.put("text", "发送成功");
            String responseMessage = responseJson.toJSONString();

            // 创建 TextWebSocketFrame 对象
            TextWebSocketFrame responseFrame = new TextWebSocketFrame(responseMessage);


        }catch (Exception e){
            System.out.println(e);

        }



    }










    private void answer(Map map) {
        String to = map.get("to").toString();
        if (cmap.containsKey("user"+to)){
            Channel channel = cmap.get("user" + to);
            Map<String,Object> obj = new HashMap<>();
            obj.put("type",7); // 回应通话
            obj.put("uuid", UUID.randomUUID().toString());
            obj.put("from",map.get("uid").toString());
            obj.put("message",map.get("message"));
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(obj)));
        }else {
            System.out.println("未登录");
        }
    }

    private void candidate(Map map) {
        String to = map.get("to").toString();
        if (cmap.containsKey("user"+to)){
            Channel channel = cmap.get("user" + to);
            Map<String,Object> obj = new HashMap<>();
            obj.put("type",8); // 回应通话
            obj.put("uuid", UUID.randomUUID().toString());
            obj.put("from",map.get("uid").toString());
            obj.put("message",map.get("message"));
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(obj)));
        }else {
            System.out.println("未登录");
        }
    }

    private void getoff(Map map) {
        String to = map.get("to").toString();
        if (cmap.containsKey("user"+to)){
            Channel channel = cmap.get("user" + to);
            Map<String,Object> obj = new HashMap<>();
            obj.put("type",6); // 回应通话
            obj.put("uuid", UUID.randomUUID().toString());
            obj.put("from",map.get("uid").toString());
            obj.put("message",map.get("message"));
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(obj)));
        }else {
            System.out.println("未登录");
        }
    }


    private void askoff(Map map) {
        String to = map.get("to").toString();
        if (cmap.containsKey("user"+to)){
            Channel channel = cmap.get("user" + to);
            Map<String,Object> obj = new HashMap<>();
            obj.put("type",5); // 回应通话
            obj.put("uuid", UUID.randomUUID().toString());
            obj.put("from",map.get("uid").toString());
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(obj)));
        }else {
            System.out.println("未登录");
        }
    }

    private void response(Map map) {
        String to = map.get("to").toString();
        if (cmap.containsKey("user"+to)){
            Channel channel = cmap.get("user" + to);
            Map<String,Object> obj = new HashMap<>();
            obj.put("type",4); // 回应通话
            obj.put("uuid", UUID.randomUUID().toString());
            obj.put("from",map.get("uid").toString());
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(obj)));
        }else {
            System.out.println("未登录");
        }
    }

    private void call(Map map) {
        String to = map.get("to").toString();
        if (cmap.containsKey("user"+to)){
            Channel channel = cmap.get("user" + to);
            Map<String,Object> obj = new HashMap<>();
            obj.put("type",3); // 对话
            obj.put("uuid", UUID.randomUUID().toString());
            obj.put("from",map.get("uid").toString());
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(obj)));
        }else {
            System.out.println("未登录");
        }
    }



    private void websocketLogin(Map map,ChannelHandlerContext ctx) {
        String uid = map.get("uid").toString();
        cmap.put("user"+uid,ctx.channel());
        System.out.println(uid+"登录");
    }

    private void sendMessage(ChannelHandlerContext ctx) throws InterruptedException {
        String message = "我是服务器，你好呀";
        ctx.writeAndFlush(new TextWebSocketFrame("hello"));
    }


//    @Override
//    protected void messageReceived(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
//
//    }
}